package com.autumn.platform.dao.page;

import org.springframework.core.NamedInheritableThreadLocal;
import org.springframework.core.NamedThreadLocal;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

public abstract class PageableHolder {

    private static final ThreadLocal<Pageable> pageableHolder =
            new NamedThreadLocal<Pageable>("Pageable");

    private static final ThreadLocal<Pageable> inheritablePageableHolder =
            new NamedInheritableThreadLocal<Pageable>("Pageable");

    private static final int DEFAULT_PAGE_SIZE = 15;

    private static int pageSize = DEFAULT_PAGE_SIZE;

    public static int getPageSize() {
        return pageSize;
    }

    public static void setPageSize(int pageSize) {
        if (pageSize > 0) {
            PageableHolder.pageSize = pageSize;
        }
    }

    public static void resetPageable() {
        pageableHolder.remove();
        inheritablePageableHolder.remove();
    }

    public static void setPageable(Pageable pageable) {
        setPageable(pageable, false);
    }

    public static void setPageable(Pageable pageable, boolean inheritable) {
        if (pageable == null) {
            resetPageable();
        } else {
            if (inheritable) {
                inheritablePageableHolder.set(pageable);
                pageableHolder.remove();
            } else {
                pageableHolder.set(pageable);
                inheritablePageableHolder.remove();
            }
        }
    }

    public static Pageable getPageable() {
        Pageable pageable = pageableHolder.get();
        if (pageable == null) {
            pageable = inheritablePageableHolder.get();
        }
        if (pageable == null) {
            pageable = PageRequest.of(0, getPageSize());
            setPageable(pageable);
        }
        return pageable;
    }
}
